<template>
    <s-layout id="layout" :title="'采购申请'" navbar="normal" leftIconColor="#ffffff" :autoBack="true" :bgColor="'rgba(0,0,0,0)'" :tabbarshow='false' :titleStyle="{ color: '#ffffff', fontSize: '32rpx',fontWeight:'600' }">
        <!-- 最大盒子 -->
        <view class="container" :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`,paddingTop:(safeAreaInsets?.top + 44) + 'px'}">
            <!-- 表单盒子 -->
            <view class="area form_box">
                <scroll-view scroll-y style="height: 70vh" :enable-back-to-top="true">
                    <u--form :labelStyle="labelStyle" labelPosition="left" :model="FormData" :rules="rules" ref="formRole" :borderBottom="false">
                        <!-- 申请事由 -->
                        <view>
                            <view class="remark"><text class="symbol">*</text>申请事由：</view>
                            <up-textarea :placeholderStyle="{color:'#999999',fontWeight: 500,fontSize:'26rpx'}" height="80" v-model="FormData.title" placeholder="请输入"></up-textarea>
                            <text class="warning" v-show="title_warning">请输入申请事由</text>
                        </view>
                        <!-- 循环 -->
                        <view v-for="(item, index) of FormData.data" :key="index">
                            <!-- 报销明细盒子 -->
                            <view class="message">
                                采购明细{{ index + 1 }}
                                <view class="glide"></view>
                                <view class="delete" @tap="deleteFormData(index)" v-show="FormData.data.length != 1">
                                    移除
                                </view>
                            </view>
                            <!-- 名称 -->
                            <u-form-item :required="true" :borderBottom="false" :labelWidth="120" label="名称：" :prop="'data.'+ index + '.price'" :ref="'data.'+ index + '.price'">
                                <u--input disabledColor="rgba(0,0,0,0)" inputAlign="right" type="text" placeholder="请输入" v-model.trim="item.title" border="none"></u--input>
                            </u-form-item>
                            <!-- 价格 -->
                            <u-form-item :required="true" :borderBottom="false" :labelWidth="120" label="价格：" :prop="'data.'+ index + '.price'" :ref="'data.'+ index + '.price'">
                                <u--input @change="inputAddition" disabledColor="rgba(0,0,0,0)" inputAlign="right" type="digit" placeholder="请输入" v-model.trim="item.price" border="none"></u--input>
                            </u-form-item>
                            <!-- 图片 -->
                            <view>
                                <view class="image">图片:</view>
                                <u-upload :fileList="state[`fileList${index}`]" @afterRead="imageUpload" @delete="deletePic" :name="index" :multiple="true" :maxCount="10">
                                </u-upload>
                            </view>
                        </view>
                        <!-- 添加报销 -->
                        <view class="add_customer" @tap="addFormData(index)">
                            +  添加采购
                        </view>
                        <!-- 备注 -->
                        <view>
                            <view class="remark">备注:</view>
                            <up-textarea :placeholderStyle="{color:'#999999',fontWeight: 500,fontSize:'26rpx'}" height="80" v-model="FormData.remark" placeholder="请输入备注"></up-textarea>
                        </view>
                        <!-- 预计金额 -->
                        <u-form-item :required="true" :borderBottom="false" :labelWidth="120" label="预计金额：" prop="price_total" ref="price_total">
                            <u--input :clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="0.00" v-model="FormData.price_total" border="none"></u--input>
                        </u-form-item>
                    </u--form>
                </scroll-view>
            </view>
        </view>
    </s-layout>

    <!-- 底部保存按钮 -->
    <view>
        <s-button @netWork="submitForm" :text="'提交'" />
    </view>
</template>

<script setup>
    import sheep from '@/sheep';
    import { ref, reactive } from 'vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { baseUrl } from "@/sheep/config";
    import { formatDate } from '@/utils/fn.js';
    import { isEmpty } from '@/sheep/helper/utils.js'
    const { safeAreaInsets } = uni.getSystemInfoSync()
    onLoad(() => {

    })

    const FormData = reactive({
        title:'',           // 申请事由
        price_total:'',     // 各项数据金额合计
        remark:'',          // 备注
        data:[{             // json数据，各项申请数据
            title:'',       // 名称
            price:'',       // 价格
            images:''       // 图片
        }]
    })

    const rules = {
        title:[
            {
                required:true,
                message:'请输入申请事由',
            }
        ],
        // price_total:[
        //     {
        //         required:true,
        //         message:'价格不能为空',
        //     }
        // ]
    }

    // 预计金额
    const inputAddition = () => {
        let a = FormData.data.reduce((prev, next) => {
			return prev + Number(next.price);
		}, 0);
		FormData.price_total = a.toFixed(2);
    }

    // 增加采购明细表单
    let annexlist = ref([
		[]
	]);
    const addFormData = (index) => {
        if(index > 5) {
            uni.showToast({
                title:'一次仅能添加五组',
                icon:'none',
                duration:1000
            })
            return false
        }

        FormData.data.push({
            title:'',       // 名称
            price:'',       // 价格
            images:''       // 图片
        });
		annexlist.value[index + 1] = [];
	}

    // 删除采购明细表单
    const deleteFormData = (index) => {
        FormData.data.splice(index,1)
        // rules.data.splice(index,1)
        inputAddition()
    }

    // 保存提交
    const formRole = ref(null)
    const title_warning = ref(false)
    const submitForm = () => {
            // #ifdef MP
            sheep.$platform.useProvider('wechat').subscribeMessage(['apply_notice','apply_result_notice']);
            // #endif
        uni.$u.throttle(() => {
        formRole.value.validate().then(async (res)=> {
            // if(FormData.title == '') {
            //     return title_warning.value = true
            // } else {
            //     title_warning.value = false
            // }
            if (isEmpty(FormData.title)) {
                await sheep.$helper.toast('请输入申请事由');
                return;
            }
            for (const item of FormData.data) {
                if (isEmpty(item.title)) {
                    await sheep.$helper.toast('请输入名称');
                    return;
                }
                if (isEmpty(item.price)) {
                    await sheep.$helper.toast('请输入价格');
                    return;
                }
            }
            const resust = await sheep.$api.purchase.postPurchaseAdd(FormData);
            if (resust.code == 1) {
                sheep.$helper.toast(resust.msg);
            setTimeout(() => {
                sheep.$router.back(true)
            }, 500)
            } else {
                sheep.$helper.toast(resust.msg);
            }
        }).catch((err) => {})
        },1000)
    }

    // 上传图片逻辑
    const state = reactive({
        fileList0: [],
        fileList1: [],
        fileList2: [],
        fileList3: [],
        fileList4: [],
    })

    // 删除图片
    const deletePic = (event) => {
        state[`fileList${event.name}`].splice(event.index, 1)
        let images = (FormData.data[event.name].images).split(',');
        images.splice(event.index, 1)
        FormData.data[event.name].images = images.join(',')
    };

    // 新增图片
    const imageUpload = async (event) => {
        let lists = [].concat(event.file);
        let fileListLen = state[`fileList${event.name}`]?.length
        lists.map((item) => {
            state[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中',
            });
        });

        let uploadFile = [];
        for (let i = 0; i < lists.length; i++) {
            let { url } = await sheep.$api.app.upload(lists[i].url, 'ugc')
            uploadFile.push(url)
            let item = state[`fileList${event.name}`][fileListLen]
            state[`fileList${event.name}`].splice(fileListLen, 1, {
                ...item,
                status: 'success',
                message: '',
                url: sheep.$url.cdn(url),
            });
            fileListLen++;
        }
        if(FormData.data[event.name].images == '') {
            let a = uploadFile
            FormData.data[event.name].images = a.join(',')
        }else {
            let a = [FormData.data[event.name].images,...uploadFile]
            FormData.data[event.name].images = a.join(',')
        }
    };

</script>

<style lang="scss" scoped>

    :deep(.u-form-item__body.data-v-b4fd400b){
        height: 80rpx;
        margin-top:30rpx;
        padding-left: 10rpx;
        background-color: #F9FAFF;
    }

    :deep(.u-textarea.data-v-31706dd7) {
        background-color: #F9FAFF;
        padding: 0;
    }

    // uview 内部样式 button 按钮边框
    :deep(.u-reset-button.data-v-05ea451b) {
        border-width: 0;
        height: 134rpx;
    }

    // uview 内部样式 up-textarea 文字距离
    :deep(.u-textarea__field.data-v-31706dd7) {
        margin-top: 30rpx;
        margin-left: 30rpx;
    }

    // uview 内部样式 输入内容右边间距
    :deep(.u-input__content__field-wrapper__field.data-v-5904192e) {
        margin-right: 20rpx;
    }

    // uview 内部样式 label左边间距
    :deep(.u-form-item__body__left.data-v-b4fd400b) {
        margin-left: 20rpx;
    }

    // uview 内部样式 label字体粗细
    :deep(.u-form-item__body__left__content__label.data-v-b4fd400b) {
        font-weight: $uni-font-weight;
    }

    // uview 内部样式 未输入提示拦截框
    :deep(.u-form-item__body__right__message.data-v-b4fd400b) {
        margin-left: 0 !important;
    }

    // uview 内部样式 选择器弹窗
    @import '../compentns/up_sheet.scss';
    

    // 最大盒子
    .container {
        width: 100%;
        background-size: cover; /* 或 contain */
    }
    // 版心
    .area {
        width: calc(100% - 40rpx);
        margin: 0 20rpx;
    }

    // 申请事由盒子
    .form_box {
        width: calc(100% - 100rpx);
        padding: 30rpx 30rpx;
        margin-top: 20rpx;
        border-radius: 16rpx;
        background-color: #FFFFFF;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
    }

    // 报销明细
    .message {
        display: flex;
        justify-content: space-between; /* 左右对齐 */
        width: 100%;
        height: 48rpx;
        margin: 30rpx 0;
        font-family: PingFangSC;
        color: $uni-text-color;
        font-weight: $uni-font-weight;
        font-size: 34rpx;
        font-style: normal;
        text-decoration: none;
        position: relative;
        align-items: center;
        .glide {
            width: 92rpx;
            height: 14rpx;
            border-radius: 5px;
            background-color: rgba(0, 56, 247, 0.5);
            position: absolute;
            bottom: 0;
            left: 20rpx;
            right: 0;
        }
        // 删除按钮
        .delete {
            font-family: PingFangSC;
            color: $uni-color-primary;
            font-weight: $uni-font-weight;
            font-size: $uni-font-size-sm;
            font-style: normal;
            text-decoration: none;
            text-align: left;
        }
    }

        // 图片
        .image {
            width: 100%;
            height: 100rpx;
            line-height: 100rpx;
            font-family: PingFangSC;
            color: $uni-text-color;
            font-weight: $uni-font-weight;
            font-size: 30rpx;
            font-style: normal;
            text-decoration: none;
        }

        // 添加报销盒子
        .add_customer {
            // width: 100%;
            height: 60rpx;
            border-radius: 16rpx;
            border: 2rpx solid $uni-color-primary;
            text-align: center;
            line-height: 60rpx;
            font-family: PingFangSC;
            color: $uni-color-primary;
            font-weight: $uni-font-weight;
            font-size: 22rpx;
            font-style: normal;
            text-decoration: none;
            margin: 30rpx 0;
        }

    // 选择日期盒子
    .date_range {
        height: 64rpx;
        width: 274rpx;
        border-radius: 16rpx;
        border: 4rpx solid #1241E2;
        display: flex;
        align-items: center;
        margin-left: 13vw;
        position: relative;
        // 图片
        .date_image {
            width: 28rpx;
            height: 28rpx;
            margin-left: 20rpx;
            margin-right: 12rpx;
            image {
                width: 100%;
                height: 100%;
            }
        }
    }

    // 时间
    .range_time {
        font-family: PingFangSC;
        color: $uni-color-primary;
        font-weight: $uni-font-weight;
       font-size:$uni-font-size-26;
        font-style: normal;
        text-decoration: none;
        text-align: right;
    }
    .icon {
        position: absolute;
        right: 30rpx;
    }

    // 报销内容
    .remark {
        width: 100%;
        height: 100rpx;
        line-height: 100rpx;
        font-family: PingFangSC;
        color: $uni-text-color;
        font-weight: $uni-font-weight;
        font-size: 30rpx;
        font-style: normal;
        text-decoration: none;
    }
    // 符号
    .symbol {
        color: #f56c6c;
    }
    // 警告
    .warning {
        font-size: $uni-font-size-sm;
        line-height: 24rpx;
        color: #f56c6c;
    }

</style>



